<?php

class FileController extends Zend_Controller_Action
{

    public function init()
    {
        Zend_Registry::get('layout')->setLayout('duty');
        
        $activeResource=$this->getRequest()->getControllerName();
        
        // seting active resource
        Zend_Registry::set('resource',$activeResource);

        $this->view->headTitle()->append(Zend_Registry::get('locale')->_('Files'));
        
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->flash_messages = $this->_flashMessenger->getMessages();
    }

    public function indexAction()
    {
        return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
    }

    /**
     * File upload action
     *
     */
    protected function addAction()
    {
        if (!Zend_Registry::get('user')->canPost())
        {
            return $this->_helper->redirector('index');
        }
        
        $form = new Application_Form_File();
        
        $request=$this->getRequest();
            
        if ($request->isPost())
        {
            if ($form->isValid($request->getPost()))
            {
                if ($form->file->receive())
                {
                    $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('File was saved'.' : '.str_replace(ROOT_DIR,'',$form->file->getFileName())));
                    
                //    return $this->_helper->redirector('add');
                    return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('file/add'));
                }
            }
            
            $this->view->message=Zend_Registry::get('locale')->_('File was not saved');
        }
            
        $this->view->form=$form;
    }
    
    /**
     * Files list action
     *
     */
    protected function listAction()
    {
        if (!Zend_Registry::get('user')->canManage())
        {
            return $this->_helper->redirector('index');
        }
        
        $key=(int) $this->_getParam('key');
        $paginator=Application_Model_File::fetchFiles($key,50);
        
        $this->view->files=$this->view->paginator=$paginator;
    }
    
    /**
     * File delete action
     *
     */
    protected function deleteAction()
    {
        if (!Zend_Registry::get('user')->canManage())
        {
            return $this->_helper->redirector('index');
        }
        
        $file=(string) $this->_getParam('file');
        
        if (Application_Model_File::delete($file))
        {
            $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('File was deleted'));
        } else 
        {
            $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('File was not deleted'));
        }
        
     //   return $this->_helper->redirector('list');
        return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('file/list'));
    }
}

